import Taro from '@tarojs/taro';
import { MaterialIcons } from 'taro-icons';
import { View, Text } from '@tarojs/components';
import React, { useEffect, useRef, useState } from 'react';

import NineImage from '../../components/NineImage';
import PageHeader from '../../components/pageHeader';
import { useAppContext } from '../../contexts/AppContext';
import ProcessTitle from '../../components/processStep/processTitle';
import ProcessStatus from '../../components/processStep/processStatus';
import { CompleteButton, NextButton } from '../../components/processStep/processButton';
import { getUserProgressStepApi, setUserProgressStepStatusApi } from '../../api/myself';

import '../user-study-time/index.scss';


const UserSubject4Appoint: React.FC = () => {
  const firstLoadRef = useRef<boolean>(false);
  const [userStep, setUserStep] = useState<any>({
    id: 0, 
    name: "", 
    status: 0, 
    completed_time: "", 
    children: []
  });
  
  // 从路由获取参数
  const stepId = Number(Taro.getCurrentInstance().router?.params?.stepId || '16');
  const subjectId = '4';
  const { setCarSubjectStepProcessStatus } = useAppContext();
  const [showTextContent, setShowTextContent] = useState('image');

  // 获取初始化信息
  const getInitInfoData = async () => {
    try {
      const res = await getUserProgressStepApi(stepId);
      if(res.code === 200 && res.data.length == 1) {
        const result = res.data[0];
        setUserStep({
          id: stepId,
          name: result.name,
          status: result.status,
          completed_time: result.created_at,
          children: result.children?.split(',') || [],
        });
      }
    } catch(err) {
      console.log(err);
      Taro.showToast({ title: '获取用户进度失败', icon: 'none' });
    }
  };

  const updateStepStatus = async () => {
    try {
      const res = await setUserProgressStepStatusApi(stepId, 1);
      if(res.code === 200) {
        setUserStep({
          ...userStep,
          status: 2
        });
        Taro.showToast({ title: '已完成科目四考试预约~', icon: 'success' });
        setCarSubjectStepProcessStatus(stepId, 1);
      }
    } catch(err) {
      console.log(err);
      Taro.showToast({ title: '预约失败，请稍后重试~', icon: 'none' });
    }
  };

  useEffect(() => {
    if (!stepId) return;
    if (!firstLoadRef.current) {
      firstLoadRef.current = true;
      getInitInfoData();
    }
  }, [stepId]);

  return (
    <View className="page-container study-time-container">
      <PageHeader title="预约科目四考试" />
      
      {userStep.completed_time && (
        <ProcessStatus title={userStep.name} createTime={userStep.completed_time} />
      )}

      <View className="study-time-content-container">
        <View className="main-card">

          <ProcessTitle 
            content="预约科目四考试"
            showTextContent={showTextContent} 
            setShowTextContent={setShowTextContent} 
          />

          <View className="study-time-steps">
            {showTextContent === 'text' && (
              <View className="steps-list">
                <View className="step-item">
                  <Text className="step-time-number">1</Text>
                  <View className="step-content">
                    <View className="step-image-container">
                      <View>打开<Text className="importance-text">交管12123APP</Text></View>
                      <View>点击更多，找到
                        <MaterialIcons name="event" color="#4F9CE0" className="calendar-icon" size={16} />
                        <Text className="importance-text">考试预约</Text>
                      </View>
                    </View>
                  </View>
                </View>
                
                <View className="step-item">
                  <Text className="step-time-number">2</Text>
                  <View className="step-content">
                    <View className="step-image-container">
                     <View>找到<Text className="importance-text">预约凭证</Text></View>
                    </View>
                  </View>
                </View>
                
                <View className="step-item">
                  <Text className="step-time-number">3</Text>
                  <View className="step-content">
                    <View className="step-image-container">
                      <View>返回主界面，找到<Text className="importance-text">更多</Text></View>
                      <View>点击<Text className="importance-text">考试费用缴纳</Text>按钮</View>
                    </View>
                  </View>
                </View>
              </View>
            )}
            {showTextContent == 'image' && (
              <NineImage images={null} stepId={stepId}/>
            )}
          </View>
        </View>
        <View className="study-time-notice">
          <View className="notice-title">
            <MaterialIcons name="info" color="#e6a23c" className="info-icon" size={16} />
            <Text className="notice-title-text text-lg">特别注意</Text>
          </View>
          <View className="notice-content">
            <View className="text-md">1、 科目三安全文明常识考试，随到随考，不用单独预约，各个地方政策存在区别</View>
            <View className="text-md">2、 部分地区需要预约；</View>
            <View className="text-md">3、 部分地区需要携带驾校档案；</View>
            <View className="text-md">4、 部分地区只需要带好有效身份证和驾驶证一寸白底照片即可；</View>
            <View className="text-md">5、 请与教练或客服老师提前沟通好。</View>
            <View className="text-md">6、 记得缴费，如果之前缴过了忽略不计。</View>
          </View>
        </View>

        <View className="button-container">
          {userStep.status === 0 ? (
            <CompleteButton content='完 成 预 约' onClick={updateStepStatus}/>
          ) : (
            <NextButton onClick={() => Taro.navigateTo({ url: `/pages/user-subject-pass/index?stepId=${stepId+1}` })} />
          )}
        </View>
      </View>
    </View>
  );
};

export default UserSubject4Appoint;